package cn.config;

import cn.entity.MapWrapperFactory;
import com.alibaba.druid.pool.DruidDataSource;
import com.github.pagehelper.PageInterceptor;
import org.mybatis.spring.SqlSessionFactoryBean;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.context.annotation.Import;
import org.springframework.web.multipart.commons.CommonsMultipartResolver;
import tk.mybatis.spring.annotation.MapperScan;

import javax.sql.DataSource;
import java.io.IOException;
import java.sql.SQLException;
import java.util.Properties;

@Configuration
@MapperScan("cn.mapper")
@Import(ServiceConfig.class)
public class MybatisConfig {

    @Bean
    public DataSource getDataSource(){
        DruidDataSource dataSource = new DruidDataSource();
        Properties properties = new Properties();
        try {
            properties.load(MybatisConfig.class.getClassLoader().getResourceAsStream("jdbc.properties"));
            dataSource.configFromPropety(properties);
            dataSource.setFilters("stat,wall");
            return dataSource;
        } catch (IOException | SQLException e) {
            e.printStackTrace();
        }
        return null;
    }

    @Bean
    public SqlSessionFactoryBean getSqlSessionFactoryBean(DataSource dataSource){
        SqlSessionFactoryBean factoryBean = new SqlSessionFactoryBean();
        factoryBean.setDataSource(dataSource);

        tk.mybatis.mapper.session.Configuration configuration = new tk.mybatis.mapper.session.Configuration();
        configuration.setCallSettersOnNulls(true);
        configuration.setMapUnderscoreToCamelCase(true);
        configuration.setObjectWrapperFactory(new MapWrapperFactory());
        factoryBean.setConfiguration(configuration);
        PageInterceptor pageInterceptor = new PageInterceptor();
        pageInterceptor.setProperties(new Properties());//设置拦截组件的方言
        factoryBean.setPlugins(pageInterceptor);//设置使用插件进行分页处理
        return factoryBean;
    }


}
